<template>
  <div style="border: 1px solid #ccc; width: 100%;">
    <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig" v-if="toolBar" />
    <Editor style="height: 500px; overflow-y: hidden;" v-model="tempValue" :defaultConfig="editorConfig"
      @onCreated="handleCreated" />
  </div>
</template>

<script lang="ts">
export default { name: 'AutumnEditor' }
</script>

<script lang="ts" setup>
import '@wangeditor/editor/dist/css/style.css'
import { onBeforeUnmount, ref, shallowRef, PropType, computed, watch } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { IEditorConfig, IDomEditor } from '@wangeditor/editor'

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()

//
const props = defineProps({
  valueHtml: {
    type: String,
    default: () => ''
  },
  toolbarConfig: {
    type: Object,
    default: () => {

    }
  },
  editorConfig: {
    type: Object as PropType<IEditorConfig>,
    default: () => {
      return {
        "MENU_CONF": {
          "uploadImage": {
            server: '#',
            maxFileSize: 1 * 1024 * 1024,
            base64LimitSize: 1 * 1024 * 1024
          }
        },
        readOnly: false
      }
    }
  },
  toolBar: {
    type: Boolean,
    default: () => true
  },
  readOnly: {
    type: Boolean,
    default: () => false
  }
})

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

//绑定数据
const tempValue = ref('')
watch(
  () => [props.valueHtml, props.readOnly],
  ([newVal1, newVal2]) => {
    tempValue.value = newVal1 as string
    const editor = editorRef.value
    if (newVal2) {
      editor.disable()
    } else {
      editor.enable()
    }
  }
)
const emits = defineEmits(['update:valueHtml'])
watch(tempValue, (newVal) => {
  emits('update:valueHtml', newVal)
})

// 记录 editor 实例，重要！
const handleCreated = (editor: IDomEditor) => {
  editorRef.value = editor
}

</script> 
